<?php

namespace app\cash\controller\goods;

use app\BaseController;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\setting\TableNumberModel;
use app\cash\controller\Order;
use app\cash\model\CartDetailModel;
use app\cash\model\CartModel;
use app\cash\model\CashSettleInfoModel;
use app\cash\model\OpenTableModel;
use app\stores\model\cash\CashOrderSetModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;

class Cart extends BaseController{
    /**
     * 赠送(未结算金额≥赠送菜品的金额就可以赠送)
     */
    public function give(){
        $cart_id = $this->request->param('cart_id/d',0);
        $origin_type = $this->request->param('origin_type/d',1);
        $give_reason = $this->request->param('give_reason');
        $give_num = $this->request->param('num/d',1);

        if($cart_id<1) return $this->error('购物车不存在');
        if(empty($give_reason)) return $this->error('原因不能为空');

        //购物车是否存在
        $cart_where = [
            'cart_id'=>$cart_id,
            'shop_id'=>$this->request->shopId,
            'origin_type'=>$origin_type,
        ];

        $cart = CartModel::getCart($cart_where);
        if(empty($cart)) return $this->error('购物车不存在');

        //赠送数量不能超过购物车数量
        if($give_num>$cart['num']) return $this->error('赠送数量不能超过购物车数量');
        //未结算金额
        //已付是否已生成订单
        if($cart['order_id']>0){
            $order = GoodsOrderModel::where(['order_id'=>$cart['order_id'],'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
            if($order){
                if($order->status==8) return $this->error('订单已完成');
                //已付
                $money = CashSettleInfoModel::where(['order_id'=>$cart['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
                $refund_money = CashSettleInfoModel::where(['order_id'=>$cart['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
                $pay_money = $money - $refund_money;
                //优惠
                $youhui_money = CashSettleInfoModel::where(['order_id'=>$cart['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
                $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_money);
                //未结算金额≥赠送菜品的金额就可以赠送
                $goods = GoodsModel::where(['goods_id'=>$cart['goods_id']])->find();
                if($cart['member_id']){
                    $member = MemberModel::where(['member_id'=>$cart['member_id']])->find();
                    if(empty($member)) return $this->error('用户不存在');
                }else{
                    $member = [];
                }
                if($cart['sku_id']){
                    $skus[] = \app\cash\model\GoodsSkuModel::info(['sku_id'=>$cart['sku_id'],'shop_id'=>$this->request->shopId,'goods_id'=>$cart['goods_id'],'is_delete'=>0]);
                    $sku_return = skuMemberPrice($goods['vip_discount_type'],$skus,$member,$goods['shop_id'],$goods['type'],$goods['origin_type'],$give_num);
                    if($sku_return){
                        $sku['price'] = sprintf("%.2f",$sku_return[0]['price']);
                        $return = $sku_return[0];
                    }
                }else{
                    //会员价格
                    $return = getMemberPrice($member,$this->request->shopId,$goods,$goods['crossed_price'],$goods['type'],0,0,$give_num);
                }
                if($un_pay_money<$return['price']) return $this->error('未结算金额小于赠送菜品的金额');
                //修改订单价格
                $order->total_price-=$return['price'];
                $order->need_pay-=$return['price'];
                $order->save();
            }
        }
        if($cart['status']==3) return $this->error('已退单');

        $data['give_num'] = $give_num;
        $data['give_reason'] = $give_reason;
        CartModel::up($data,$cart_where);

        if($cart['table_number_id']){
            $s_data['data']['open_table_id'] = $cart['open_table_id'];
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }
        return $this->success('赠送成功');

    }
    /**
     * 撤销所有赠送(订单完成结账后不能撤销)
     */
    public function revokeGive(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $revoke_give_reason = $this->request->param('revoke_give_reason');
        $origin_type = $this->request->param('origin_type/d',1);

        if(empty($revoke_give_reason)) return $this->error('取消赠送原因不能为空');
        if($is_fit<1 && $member_id<1) return $this->error('不是散客时需要传用户id');

        Db::startTrans();
        try{
            $table_number_id = 0;
            $where['origin_type'] = $origin_type;
            $where['shop_id'] = $this->request->shopId;
            $where['is_give'] = 1;
            $where['is_delete'] = 0;
            $where['status'] = array('<>',3);
            //有开台
            if($open_table_id){
                $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
                if(empty($ot)) return $this->error('开台不存在');
                $table_number_id = $ot['table_number_id'];
                $where['table_number_id'] = $table_number_id;
                $where['open_table_id'] = $open_table_id;
                $list = CartModel::list($where);
                CartModel::up(['is_delete'=>1,'revoke_give_reason'=>$revoke_give_reason],$where);
            }else{
                //是散客
                if($is_fit){
                    if($table_number_id<1) $where['account_id'] = $this->request->accountId;
                    $where['table_number_id'] = 0;
                    $where['open_table_id'] = 0;
                    $where['member_id'] = 0;
                    $where['is_fit'] = $is_fit;
                    $list = CartModel::list($where);
                    CartModel::up(['is_delete'=>1,'revoke_give_reason'=>$revoke_give_reason],$where);
                }else{
                    $where['account_id'] = $this->request->accountId;
                    $where['member_id'] = $member_id;
                    $where['open_table_id'] = 0;
                    $where['table_number_id'] = 0;
                    $where['is_fit'] = 0;
                    $list = CartModel::list($where);
                    CartModel::up(['is_delete'=>1,'revoke_give_reason'=>$revoke_give_reason],$where);
                }

            }

//            if($list){
//                foreach ($list as $k=>$v){
//                    $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$v['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
//                    if($goods){
//                        $data['quota'] = $goods['quota'] + $v['num'];
//                        \app\cash\model\GoodsModel::up($data,['goods_id'=>$v['goods_id']]);
//                    }
//                }
//            }

            if($table_number_id){
                $s_data['data']['open_table_id'] = $open_table_id;
                $s_data['type'] = 'cart';
                pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
            }
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('撤销成功');

    }
    /**
     * 向购物车中添加/修改商品(在没有生订单之前都可以加购物车)
     */
    public function save()
    {
        //套餐只能选一次
        $is_fit = $this->request->param('is_fit/d',0);
        $service_type = $this->request->param('service_type/d',1);
        //$table_number_id = $this->request->param('table_number_id/d',0);
        $goods_id = $this->request->param('goods_id/d',0);
        $sku_id = $this->request->param('sku_id/d',0);
        $num = $this->request->param('num/d',1);
        $origin_type = $this->request->param('origin_type/d',1);
        $member_id = $this->request->param('member_id/d',0);
        $goods_group_detail_id = $this->request->param('goods_group_detail_id/a',[]);
        $open_table_id = $this->request->param('open_table_id/d',0);
        $order_id = 0;$member=[];
        if($is_fit<1){
            $member = MemberModel::where(['member_id'=>$member_id])->find();
            if(empty($member)) return $this->error('用户不存在');
        }
        if($goods_id<1) return $this->error('产品不存在');
        if($num<1) return $this->error('数量不能小于1');
        $table_number_id = 0;
        if($open_table_id){
            $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
            if(empty($ot)) return $this->error('开台不存在');
            $table_number_id = $ot['table_number_id'];
            $table = TableNumberModel::info(['id'=>$table_number_id,'shop_id'=>$this->request->shopId]);
            if(empty($table)) return $this->error('桌台不存在');
            if($table['is_effect']<1) return $this->error('桌台无效');
        }

        $where = [
            'shop_id'=>$this->request->shopId,
            'goods_id'=>$goods_id,
            'is_delete'=>0,
            'origin_type'=>2
        ];
        // 获取商品信息
        $goodsModel = new GoodsModel();
        $goods = $goodsModel->getById($where);

        if(!$goods) return $this->error('产品不存在');

        if($goods['type']==3 && empty($goods_group_detail_id)) return $this->error('套餐内容不能为空');

        if($goods['type']==3 && $num>1) return $this->error('套餐数量只能为1');

        if($goods['is_have_sku'] && $sku_id<1) return $this->error('多规格产品需要选规格');

        if($goods['type']==2 && $num<$goods['start_sales_num']) return $this->error('数量必须大于起售量');

        if($goods['type']==2 && $num>$goods['max_num']) return $this->error('数量超过最多点菜量');

        //库存判断
        $set = CashOrderSetModel::info(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        $quota = ($set['day_quota_type']==1)?999:$goods['quota'];
        if($num>$quota) return $this->error('库存不足');

        if($sku_id){
            unset($where['origin_type']);
            $sku_where = $where;
            $sku_where['sku_id'] = $sku_id;
            $goodsSkuModel = new GoodsSkuModel();
            $sku = $goodsSkuModel->getById($sku_where);
            if(!$sku){
                return $this->error('产品不存在');
            }

        }
        //是否已生成订单
        $cart_order_where[] = ['is_fit','=',$is_fit];
        $cart_order_where[] = ['service_type','=',$service_type];
        $cart_order_where[] = ['open_table_id','=',$open_table_id];
        $cart_order_where[] = ['table_number_id','=',$table_number_id];
        $cart_order_where[] = ['shop_id','=',$this->request->shopId];
        $cart_order_where[] = ['member_id','=',$member_id];
        $cart_order_where[] = ['is_delete','=',0];
        $cart_order_where[] = ['origin_type','=',$origin_type];
        $cart_order_where[] = ['account_id','=',$this->request->accountId];
        $cart_order_where[] = ['order_id','>',0];
        $cart_order = CartModel::getCart($cart_order_where);
        if($cart_order){
            $order = GoodsOrderModel::where(['shop_id'=>$this->request->shopId,'order_id'=>$cart_order['order_id']])->find();
            if($order['status']==8) return $this->error('已结账操作，无法添加');
            $order_id = $cart_order['order_id'];
        }

        //购物车是否存在
        $cart_where = [
            'is_fit'=>$is_fit,
            'service_type'=>$service_type,
            'open_table_id'=>$open_table_id,
            'table_number_id'=>$table_number_id,
            'shop_id'=>$this->request->shopId,
            'goods_id'=>$goods_id,
            'sku_id'=>$sku_id,
            'member_id'=>$member_id,
            'is_give'=>0,
            'is_delete'=>0,
            'origin_type'=>$origin_type,
            //'type'=>2,
            'account_id'=>$this->request->accountId,
        ];

        $cart = CartModel::getCart($cart_where);

        if($cart){
            if($goods['type']==3) return $this->error('套餐只能选购一次');
            $data['num'] = $num + $cart['num'];
            $data['status'] = $cart['confirm_num']>0?2:0;
            CartModel::up($data,['cart_id'=>$cart['cart_id']]);
        }else{
            $data['is_fit'] = $is_fit;
            $data['service_type'] = $service_type;
            $data['open_table_id'] = $open_table_id;
            $data['table_number_id'] = $table_number_id;
            $data['shop_id'] = $this->request->shopId;
            $data['goods_id'] = $goods_id;
            $data['sku_id'] = $sku_id;
            $data['member_id'] = $member_id;
            $data['num'] = $num;
            $data['origin_type'] = $origin_type;
            $data['type'] = $goods['type'];
            $data['account_id'] = $this->request->accountId;
            $data['add_ip'] = request()->ip();
            $data['order_id'] = $order_id;
            $cart_id = CartModel::insertGetId($data);
            if($goods['type']==3){
                $cd_mode = new CartDetailModel();
                for($i=0;$i<count($goods_group_detail_id);$i++){
                    $cd_mode->shop_id = $this->request->shopId;
                    $cd_mode->member_id = $member_id;
                    $cd_mode->cart_id = $cart_id;
                    $cd_mode->goods_group_detail_id = $goods_group_detail_id[$i];
                    $cd_mode->save();
                }

            }
        }
        //是否已生成订单（需要修改金额）
        if($order_id && $order){
            $return = getMemberPrice($member,$this->request->shopId,$goods,$goods['crossed_price'],$goods['type'],0,0,$num);
            if($sku_id){
                $sku_where = [
                    'sku_id'=>$sku_id,
                    'goods_id'=>$goods_id
                ];
                $sku = $goodsSkuModel->getById($sku_where,'name,goods_id,crossed_price,discount_detail,quota,start_sales_num');
                if($sku){
                    $sku['discount_detail'] = $sku['discount_detail'];
                    $sku['original_price'] = $sku['crossed_price'];
                    $sku['origin_type'] = $order['origin_type'];
                    $skus[] = $sku;
                    if($member){
                        $sku_return = skuMemberPrice($goods['vip_discount_type'],$skus,$member,$goods['shop_id'],$goods['type'],$goods['origin_type'],$num);
                        if($sku_return){
                            $sku['price'] = sprintf("%.2f",$sku_return[0]['price']);
                            $return = $sku_return[0];
                        }
                    }else{
                        $sku['price'] = sprintf("%.2f",$sku['crossed_price']) * $num;
                        $return['price'] = $sku['price'];
                    }

                }

            }
            $order->total_price += $return['price'];
            $order->need_pay += $return['price'];
            $order->save();
        }
        //推送
        if($table_number_id){
            $s_data['data']['open_table_id'] = $open_table_id;
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }
        //修改库存
//        if($set['day_quota_type']!=1){
//            goodsModel::up(['quota'=>$goods['quota']-$num,'update_time'=>time()],['goods_id'=>$goods_id,'shop_id'=>$this->request->shopId]);
//        }

        return $this->success('添加成功');
    }
    /**
     * 删除购物车（只能删未落单的菜品（退单的也不能删除））
     */
    public function del()
    {
        $cart_id = $this->request->param('cart_id/d',0);
        $origin_type = $this->request->param('origin_type/d',1);

        if($cart_id<0)  return $this->success('删除成功');
        Db::startTrans();
        try{
            $cart = CartModel::getCart(['cart_id'=>$cart_id,'origin_type'=>$origin_type,'shop_id'=>$this->request->shopId]);
            if($cart['type']==3) CartDetailModel::update(['is_delete'=>1],['cart_id'=>$cart_id]);
            CartModel::up(['is_delete'=>1],['cart_id'=>$cart_id,'origin_type'=>$origin_type]);
            //加回库存
            $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$cart['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
            if($goods){
                $data['quota'] = $goods['quota'] + $cart['num'];
                \app\cash\model\GoodsModel::up($data,['goods_id'=>$cart['goods_id']]);
            }
            if($cart['table_number_id']){
                $s_data['data']['open_table_id'] = $cart['open_table_id'];
                $s_data['type'] = 'cart';
                pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
            }
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('删除成功');
    }

    /**
     * 清空购物车（只能删未落单的菜品（退单的也不能删除））
     */
    public function delAll()
    {
        $open_table_id = $this->request->param('open_table_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $origin_type = $this->request->param('origin_type/d',1);

        $where['origin_type'] = $origin_type;
        $where['account_id'] = $this->request->accountId;
        $where['shop_id'] = $this->request->shopId;
        $where['is_delete'] = 0;
        if($open_table_id){
            $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
            if(empty($ot)) return $this->error('开台不存在');
            $table_number_id = $ot['table_number_id'];
            $where['table_number_id'] = $table_number_id;
            $where['open_table_id'] = $open_table_id;
            $list = CartModel::list($where);
            CartModel::up(['is_delete'=>1],$where);
        }else{
            if($is_fit){
                $where['table_number_id'] = 0;
                $where['open_table_id'] = 0;
                $where['member_id'] = 0;
                $where['is_fit'] = $is_fit;
                $list = CartModel::list($where);
                CartModel::up(['is_delete'=>1],$where);
            }else{
                $where['member_id'] = $member_id;
                $where['table_number_id'] = 0;
                $where['open_table_id'] = 0;
                $where['is_fit'] = 0;
                $list = CartModel::list($where);
                CartModel::up(['is_delete'=>1],$where);
            }

        }

//        if($list){
//            foreach ($list as $k=>$v){
//                $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$v['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
//                if($goods){
//                    $data['quota'] = $goods['quota'] + $v['num'];
//                    \app\cash\model\GoodsModel::up($data,['goods_id'=>$v['goods_id']]);
//                }
//            }
//        }
        if($table_number_id){
            $s_data['data']['open_table_id'] = $open_table_id;
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }
        return $this->success('删除成功');
    }
    /**
     * 列表
     */
    public function list(){
        $is_fit = $this->request->param('is_fit/d',0);
        $service_type = $this->request->param('service_type/d',1);
        $open_table_id = $this->request->param('open_table_id/d',0);
        $origin_type = $this->request->param('origin_type/d',1);
        $member_id = $this->request->param('member_id/d',0);

        if(!in_array($service_type,[1,2,3])) return $this->error('就餐方式不存在');

        if($is_fit<1){
            if($member_id<1) return $this->error('用户不存在');
            $member_model = new MemberModel();
            $member = $member_model->getById(['member_id'=>$member_id]);
            if(empty($member)) return $this->error('用户不存在');
        }else{
            $member = [];
        }
        $table_number_id = 0;
        if($open_table_id>0){
            $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
            if(empty($ot)) return $this->error('开台不存在');
            $table_number_id = $ot['table_number_id'];
            $table = TableNumberModel::info(['id'=>$table_number_id,'shop_id'=>$this->request->shopId]);
            if(empty($table)) return $this->error('桌台不存在');
            if($table['is_effect']<1) return $this->error('桌台无效');

            $ot = OpenTableModel::getById(['table_number_id'=>$table_number_id,'status'=>0,'is_delete'=>0]);
            if(empty($ot)) return $this->error('没有开台');
        }
        $where['is_fit'] = $is_fit;
        $where['service_type'] = $service_type;
        $where['table_number_id'] = $table_number_id;
        $where['open_table_id'] = $open_table_id;
        $where['member_id'] = $member_id;
        $where['origin_type'] = $origin_type;
        $where['shop_id'] = $this->request->shopId;
        if($table_number_id<1) $where['account_id'] = $this->request->accountId;
        $field = 'c.*,g.cover_img,g.origin_type,g.name,g.type,g.discount_detail,g.crossed_price,g.crossed_price,g.max_num,g.start_sales_num,g.vip_discount_type,g.cover_img,g.quota,
        g.status,g.is_vip_discount,d.group_detail_name as unit_name,g.is_delete as goods_id_delete';
        $order = ['c.add_time'=>'desc'];
        $return = CartModel::getCashCartlist($member,$where,$order,$this->request->page,$this->request->limit,$field);
        $return['remarks'] = isset($ot)?$ot['remarks']:NULL;
        $un_pay_money = $return['total_price'];
        //已付
        //是否已生成订单
        $cart_order = CartModel::where($where)->where('order_id','>',0)->find();
        if($cart_order){
            $order = GoodsOrderModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
            if($order){
                //已付
                $money = CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('money');
                $refund_money = CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>1,'is_delete'=>0])->sum('refund_money');
                $pay_money = $money - $refund_money;
                //优惠
                $youhui_money = CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$this->request->shopId,'info_type'=>2,'is_delete'=>0])->sum('money');
                $return['youhui_price']+=$youhui_money;
                $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $return['youhui_price']);
            }

        }
        //未支付
        $return['un_pay_price'] = $un_pay_money;
        $return['pay_price'] = isset($pay_money)?sprintf("%.2f",$pay_money):0;
        $return['order_id'] = $return['list']?$return['list'][0]['order_id']:0;
        return $this->success($return);
    }
    /**
     * 改价
     */
    public function updatePrice(){
        $cart_id = $this->request->param('cart_id/d',0);
        $update_price = $this->request->param('update_price/f',0);
        $update_price_reason = $this->request->param('update_price_reason');
        $origin_type = $this->request->param('origin_type/d',1);

        if($cart_id<1) return $this->error('购物车不存在');
        if(empty($update_price_reason)) return $this->error('原因不能为空');

        //购物车是否存在
        $cart_where = [
            'cart_id'=>$cart_id,
            'shop_id'=>$this->request->shopId,
            'origin_type'=>$origin_type,
        ];

        $cart = CartModel::getCart($cart_where);
        if(empty($cart)) return $this->error('购物车不存在');

        $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$cart['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
        if(empty($goods)) return $this->error('产品不存在');

        $data = [];
        if($cart['member_id']){
            $member = MemberModel::info(['member_id'=>$cart['member_id']]);
            if($member){
                if($cart['sku_id']){
                    $skus[] = \app\cash\model\GoodsSkuModel::info(['sku_id'=>$cart['sku_id'],'shop_id'=>$this->request->shopId,'goods_id'=>$cart['goods_id'],'is_delete'=>0]);
                    $return = skuMemberPrice($goods['vip_discount_type'],$skus,$member,$goods['shop_id'],$goods['type'],$goods['origin_type'],$cart['num']);
                    if($return){
                        $price = sprintf("%.2f",$return[0]['price']);
                    }
                }else{
                    $return = getMemberPrice($member,$this->request->shopId,$goods,$goods['crossed_price'],$goods['type'],$cart['num']);
                    if($return){
                        $price = sprintf("%.2f",$return['price']);
                    }
                }

            }
            if(isset($price) && $update_price<$price){
                $data['price'] = $update_price;
                $data['update_price_reason'] = $update_price_reason;
            }
        }else{
            $price = $goods['crossed_price'];
            if($cart['sku_id']) {
                $skus = \app\cash\model\GoodsSkuModel::info(['sku_id' => $cart['sku_id'], 'shop_id' => $this->request->shopId, 'goods_id' => $cart['goods_id'], 'is_delete' => 0]);
                $price = $skus['crossed_price'];
            }
            if($update_price<$price){
                $data['price'] = $update_price;
                $data['update_price_reason'] = $update_price_reason;
            }
        }

        CartModel::up($data,['cart_id'=>$cart_id,'shop_id'=>$this->request->shopId]);

        if($cart['table_number_id']){
            $s_data['data']['open_table_id'] = $cart['open_table_id'];
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }

        return $this->success('修改成功');
    }
    /**
     *减少或增加
     */
    public function updateNum(){
        $cart_id = $this->request->param('cart_id/d',0);
        $type = $this->request->param('type/d',1);//1增加2减少
        $origin_type = $this->request->param('origin_type/d',1);

        if($cart_id<1) return $this->error('购物车不存在');

        //购物车是否存在
        $cart_where = [
            'cart_id'=>$cart_id,
            'shop_id'=>$this->request->shopId,
            'account_id'=>$this->request->accountId,
            'origin_type'=>$origin_type,
        ];

        $cart = CartModel::getCart($cart_where);
        if(empty($cart)) return $this->error('购物车不存在');

        $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$cart['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
        if(empty($goods)) return $this->error('产品不存在');

        if($type==1){
            $data['num'] = $cart['num'] + 1;
        }else{
            $data['num'] = $cart['num'] - 1;
        }
        if($data['num']<$goods['start_sales_num']) return $this->error('数量必须大于起售量'.$goods['start_sales_num']);
        if($data['num']>$goods['max_num'] && $goods['max_num']>-1) return $this->error('数量必须小于最多点菜量'.$goods['max_num']);
        if($data['num']<0) return $this->error('购买数量不能少于1');

        CartModel::up($data,['cart_id'=>$cart_id]);

        if($cart['table_number_id']){
            $s_data['data']['open_table_id'] = $cart['open_table_id'];
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }
        return $this->success('修改成功');
    }

    /**
     *改量
     */
    public function editNum(){
        $cart_id = $this->request->param('cart_id/d',0);
        $num = $this->request->param('num/d',0);
        $origin_type = $this->request->param('origin_type/d',1);

        if($cart_id<1) return $this->error('购物车不存在');
        if($num<1) return $this->error('数量不能小于1');

        //购物车是否存在
        $cart_where = [
            'cart_id'=>$cart_id,
            'shop_id'=>$this->request->shopId,
            //'account_id'=>$this->request->accountId,
            'origin_type'=>$origin_type,
        ];

        $cart = CartModel::getCart($cart_where);
        if(empty($cart)) return $this->error('购物车不存在');

        $goods = \app\cash\model\GoodsModel::info(['goods_id'=>$cart['goods_id'],'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
        if(empty($goods)) return $this->error('产品不存在');

        if($num<$goods['start_sales_num']) return $this->error('数量必须大于起售量'.$goods['start_sales_num']);
        if($num>$goods['max_num'] && $goods['max_num']>-1) return $this->error('数量必须小于最多点菜量'.$goods['max_num']);

        $data['num'] = $num;
        CartModel::up($data,['cart_id'=>$cart_id]);

        if($cart['table_number_id']){
            $s_data['data']['open_table_id'] = $cart['open_table_id'];
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
        }
        return $this->success('修改成功');
    }

    /**
     * 购物车修改散客状态（生成订单后没有结算记录才可修改散客状态）
     */
    public function updateFit(){
        $order_id = $this->request->param('order_id/d',0);
        $open_table_id = $this->request->param('open_table_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $member_id = $this->request->param('member_id/d',0);

        if($order_id){
            $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
            if(empty($order)) return $this->error('订单不存在');
            if(!in_array($order['status'],[1,15,16])) return $this->error('该订单不能编辑');
            $cart_where[] = ['order_id','=',$order_id];
        }
        if($open_table_id){
            $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
            if(empty($ot)) return $this->error('开台不存在');
            $cart_where[] = ['open_table_id','=',$open_table_id];
        }
        if($is_fit){
            $member_id = 0;
        }else{
            if($member_id<1) return $this->error('用户不存在');
            $member = MemberModel::where(['member_id'=>$member_id])->find();
            if(empty($member)) return $this->error('用户不存在');
        }
        $cart_where[] = ['member_id','=',$member_id];
        $cart_where[] = ['is_fit','=',$is_fit];

        Db::startTrans();
        try{
            //修改购物车
            $cart_where[] = ['shop_id','=',$this->request->shopId];
            $cart_where[] = ['is_delete','=',0];
            CartModel::up(['is_fit'=>$is_fit,'member_id'=>$member_id],$cart_where);
            //如果有开台修改开台
            if($open_table_id){
                $ot_where[] = ['open_table_id','=',$open_table_id];
                $ot_where[] = ['status','=',0];
                $ot_where[] = ['is_delete','=',0];
                $ot_where[] = ['shop_id','=',$this->request->shopId];
                OpenTableModel::update(['is_fit'=>$is_fit,'member_id'=>$member_id],$ot_where);
            }
            if($order_id){
                //判断已有结算信息的订单不能修改散客状态
                $settle_info = CashSettleInfoModel::getById(['order_id'=>$order_id]);
                if($settle_info) return $this->error('也有结算信息，不能修改散客状态');
            }
            //推送
            $s_data['data']['open_table_id'] = $open_table_id;
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);
            Db::commit();

            return $this->success('设置成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
    /**
     * 全部退菜（如果存在一个产品数量大于1：退已落单的,未落单的直接删除，修改购物车数量）
     */
    public function allReturn(){
        $is_fit = $this->request->param('is_fit/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $open_table_id = $this->request->param('open_table_id/d',0);
        if($open_table_id){
            $ot = OpenTableModel::getById(['open_table_id'=>$open_table_id,'status'=>0,'shop_id'=>$this->request->shopId]);
            if(empty($ot)) return $this->error('开台不存在');
            $cart_where[] = ['open_table_id','=',$open_table_id];
        }else{
            if($is_fit){
                $member_id = 0;
            }else{
                if($member_id<1) return $this->error('用户不存在');
                $member = MemberModel::where(['member_id'=>$member_id])->find();
                if(empty($member)) return $this->error('用户不存在');
            }
            $cart_where[] = ['member_id','=',$member_id];
            $cart_where[] = ['is_fit','=',$is_fit];
        }
        $cart_where[] = ['status','in',[1,2]];//1全部落单2部分落单
        $cart_where[] = ['is_delete','=',0];
        $cart_where[] = ['shop_id','=',$this->request->shopId];
        $cart_list = CartModel::list($cart_where);

        Db::startTrans();
        try{
            foreach ($cart_list as $k=>$v){
                if($v['status']==2){
                    CartModel::up(['num'=>$v['confirm_num']]);
                }
            }
            CartModel::up(['status'=>3],$cart_where);

            Db::commit();

            return $this->success('退菜成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }
}

